<template>
  <el-dialog
    :model-value="modelValue"
    :title="isEditMode ? '编辑版本' : '新建版本'"
    width="720px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
    class="version-dialog"
  >
    <div v-loading="loadingVersion" class="dialog-content">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="110px"
        label-position="left"
        status-icon
        class="version-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon class="section-icon"><Document /></el-icon>
            <span>基本信息</span>
          </div>
          <el-form-item label="版本名称" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入版本名称，如：春季版本、V2.0 等"
              maxlength="80"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="版本号" prop="version_number">
            <el-input
              v-model="form.version_number"
              placeholder="例如：1.0.0 或 v1.0.0"
              maxlength="40"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="所属项目" prop="project_id">
            <el-select
              v-model="form.project_id"
              placeholder="请选择项目"
              filterable
              remote
              :remote-method="filterProjects"
              :loading="projectsLoading"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="project in filteredProjects"
                :key="project.id"
                :label="project.name"
                :value="project.id"
              />
            </el-select>
          </el-form-item>
        </div>

        <!-- 版本配置 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon class="section-icon"><Setting /></el-icon>
            <span>版本配置</span>
          </div>
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="状态" prop="status">
                <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                  <el-option
                    v-for="option in versionStatusOptions"
                    :key="option.value"
                    :label="option.label"
                    :value="option.value"
                  >
                    <span style="display: flex; align-items: center; gap: 8px">
                      <span
                        class="status-dot"
                        :style="{ backgroundColor: option.color || '#909399' }"
                      />
                      <span>{{ option.label }}</span>
                    </span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发布类型" prop="release_type">
                <el-select v-model="form.release_type" placeholder="请选择类型" style="width: 100%">
                  <el-option
                    v-for="item in releaseTypeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="部署环境" prop="environment">
                <el-select v-model="form.environment" placeholder="请选择环境" style="width: 100%">
                  <el-option
                    v-for="item in environmentOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="计划发布" prop="planned_release_date">
                <el-date-picker
                  v-model="form.planned_release_date"
                  type="datetime"
                  value-format="YYYY-MM-DDTHH:mm:ss"
                  placeholder="选择计划发布时间"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="计划工时">
            <el-input-number
              v-model="form.planned_work_hours"
              :min="0"
              :step="1"
              :precision="0"
              controls-position="right"
              style="width: 100%"
              placeholder="预计工时（小时）"
            >
              <template #suffix>小时</template>
            </el-input-number>
          </el-form-item>
        </div>

        <!-- 版本描述 -->
        <div class="form-section">
          <div class="section-title">
            <el-icon class="section-icon"><EditPen /></el-icon>
            <span>版本描述</span>
          </div>
          <el-form-item label="描述信息">
            <el-input
              v-model="form.description"
              type="textarea"
              :rows="4"
              maxlength="200"
              show-word-limit
              placeholder="可选，补充版本目标、要点或说明..."
              resize="none"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" size="large">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit" size="large">
          <el-icon v-if="!submitting" class="button-icon">
            <Check v-if="isEditMode" />
            <Plus v-else />
          </el-icon>
          {{ isEditMode ? '保存更改' : '创建版本' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, nextTick, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Document, Setting, EditPen, Check, Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import {
  Environment,
  ReleaseType,
  type Version,
  type VersionCreate,
  type VersionStatus,
  versionAPI
} from '@/api/version'
import { projectAPI } from '@/api/project'
import type { Project } from '@/types/project'
import { ResponseParser } from '@/utils/responseParser'
import { formatDate } from '@/utils/date'
import { useVersionStates } from '@/composables/useVersionStates'

interface VersionCreateForm extends Omit<VersionCreate, 'goals' | 'release_config' | 'metadata'> {
  description?: string
}

const props = defineProps<{
  modelValue: boolean
  versionId?: string
  version?: Version | null
}>()

const emit = defineEmits<{
  (event: 'update:modelValue', value: boolean): void
  (event: 'created', value: Version): void
  (event: 'updated', value: Version): void
}>()

const formRef = ref<FormInstance>()
const submitting = ref(false)
const projectsLoading = ref(false)
const loadingVersion = ref(false)
const projectOptions = ref<Project[]>([])
const projectKeyword = ref('')

const { statusOptions, defaultState } = useVersionStates()

const isEditMode = computed(() => !!props.versionId || !!props.version)

const versionStatusOptions = computed(() => {
  // 编辑模式下显示所有状态，创建模式下只显示部分状态
  if (isEditMode.value) {
    return statusOptions.value.map(option => ({
      label: option.label,
      value: option.value as VersionStatus,
      color: option.color
    }))
  }
  // 创建时只显示早期状态（草稿、规划中、开发中等）
  // 根据状态名称关键词动态过滤
  return statusOptions.value
    .filter(option => {
      const statusName = option.label.toLowerCase()
      // 判断是否为早期状态（包含"草稿"、"规划"、"开发"等关键词）
      return statusName.includes('草稿') || statusName.includes('规划') || statusName.includes('开发')
    })
    .map(option => ({
      label: option.label,
      value: option.value as VersionStatus,
      color: option.color
    }))
})

const releaseTypeOptions = [
  { value: ReleaseType.MAJOR, label: '主版本' },
  { value: ReleaseType.MINOR, label: '次版本' },
  { value: ReleaseType.PATCH, label: '补丁' },
  { value: ReleaseType.HOTFIX, label: '热修复' }
]

const environmentOptions = [
  { value: Environment.DEVELOPMENT, label: '开发环境' },
  { value: Environment.TESTING, label: '测试环境' },
  { value: Environment.STAGING, label: '预发布环境' },
  { value: Environment.PRODUCTION, label: '生产环境' }
]

const form = reactive<VersionCreateForm>({
  name: '',
  version_number: '',
  project_id: '',
  status: defaultState.value?.code || '',
  release_type: ReleaseType.MINOR,
  environment: Environment.DEVELOPMENT,
  planned_release_date: undefined,
  planned_work_hours: undefined,
  description: ''
})

const rules: FormRules<VersionCreateForm> = {
  name: [
    { required: true, message: '请输入版本名称', trigger: 'blur' },
    { min: 2, max: 80, message: '名称长度需在 2-80 个字符之间', trigger: 'blur' }
  ],
  version_number: [
            { required: true, message: '请输入版本号', trigger: 'blur' },
            { min: 1, max: 40, message: '版本号长度在 1 到 40 个字符之间', trigger: 'blur' },
            { pattern: /^[0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9]+)?(?:\.[a-zA-Z0-9]+)?$/, message: '版本号格式不正确，应为 x.y.z 格式', trigger: 'blur' }
          ],
  project_id: [{ required: true, message: '请选择所属项目', trigger: 'change' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  release_type: [{ required: true, message: '请选择发布类型', trigger: 'change' }],
  environment: [{ required: true, message: '请选择部署环境', trigger: 'change' }],
  planned_release_date: [
    {
      validator: (_, value, callback) => {
        if (!value) {
          callback()
          return
        }
        callback()
      },
      trigger: 'change'
    }
  ]
}

const filteredProjects = computed(() => {
  if (!projectKeyword.value) return projectOptions.value
  const keyword = projectKeyword.value.toLowerCase()
  return projectOptions.value.filter(project =>
    project.name?.toLowerCase().includes(keyword)
  )
})

watch(
  () => [props.modelValue, props.versionId, props.version] as const,
  ([visible, versionId, version]) => {
    if (visible) {
      nextTick(() => {
        if (versionId) {
          loadVersionData(versionId)
        } else if (version) {
          loadVersionData(version.id)
        } else {
          resetForm()
        }
        loadProjects()
      })
    } else {
      resetForm()
    }
  }
)

const loadProjects = async () => {
  if (projectsLoading.value) return
  projectsLoading.value = true
  try {
    const response = await projectAPI.getProjects({ page: 1, size: 100 })
    const parsed = ResponseParser.parseListResponse<Project>(response)
    projectOptions.value = parsed.items.filter(
      (project): project is Project => !!project?.id && !!(project.name || project.description)
    )
    projectKeyword.value = ''
  } catch (error) {
    console.error('加载项目列表失败', error)
    const message = ResponseParser.extractMessage(error) || '加载项目列表失败，请稍后重试'
    ElMessage.error(message)
    projectOptions.value = []
  } finally {
    projectsLoading.value = false
  }
}

const filterProjects = (keyword: string) => {
  projectKeyword.value = keyword
}

const loadVersionData = async (id?: string) => {
  if (!id) {
    // 如果直接传入了 version 对象，直接使用
    if (props.version) {
      fillFormFromVersion(props.version)
      return
    }
    return
  }

  loadingVersion.value = true
  try {
    const response = await versionAPI.getVersionById(id)
    if (response.success && response.data) {
      fillFormFromVersion(response.data)
    } else {
      ElMessage.error(response.message || '获取版本信息失败')
    }
  } catch (error) {
    console.error('获取版本信息失败:', error)
    ElMessage.error('获取版本信息失败')
  } finally {
    loadingVersion.value = false
  }
}

const fillFormFromVersion = (version: Version | any) => {
  form.name = version.name || ''
  form.version_number = version.version_number || ''
  form.project_id = version.project_id || ''
  form.status = version.status || defaultState.value?.code || ''
  form.release_type = version.release_type || ReleaseType.MINOR
  form.environment = version.environment || Environment.DEVELOPMENT
  form.planned_release_date = version.planned_release_date
    ? formatDate(version.planned_release_date, 'YYYY-MM-DDTHH:mm:ss')
    : undefined
  form.planned_work_hours = version.planned_work_hours || undefined
  form.description = version.description || ''
}

const handleSubmit = async () => {
  if (!formRef.value) {
    return
  }
  await formRef.value.validate(async valid => {
    if (!valid) {
      return
    }
    submitting.value = true
    try {
      const versionId = props.versionId || props.version?.id
      
      if (isEditMode.value && versionId) {
        // 编辑模式
        const payload = {
          name: form.name.trim(),
          version_number: form.version_number.trim(),
          project_id: form.project_id,
          status: form.status,
          release_type: form.release_type,
          environment: form.environment,
          planned_release_date: form.planned_release_date ? new Date(form.planned_release_date).toISOString() : undefined,
          planned_work_hours:
            form.planned_work_hours !== undefined ? Number(form.planned_work_hours) : undefined,
          description: form.description?.trim() || undefined
        }

        const response = await versionAPI.updateVersion(versionId, payload)
        if (!response.success || !response.data) {
          const message = response.message || '更新版本失败，请稍后重试'
          throw new Error(message)
        }

        ElMessage.success('版本更新成功')
        emit('updated', response.data)
        emit('update:modelValue', false)
        resetForm()
      } else {
        // 创建模式
        const payload: VersionCreate = {
          name: form.name.trim(),
          version_number: form.version_number.trim(),
          project_id: form.project_id,
          status: form.status,
          release_type: form.release_type,
          environment: form.environment,
          planned_release_date: form.planned_release_date ? new Date(form.planned_release_date).toISOString() : undefined,
          planned_work_hours:
            form.planned_work_hours !== undefined ? Number(form.planned_work_hours) : undefined,
          description: form.description?.trim() || undefined
        }

        const response = await versionAPI.createVersion(payload)
        if (!response.success || !response.data) {
          const message = response.message || '创建版本失败，请稍后重试'
          throw new Error(message)
        }

        ElMessage.success('版本创建成功')
        emit('created', response.data)
        emit('update:modelValue', false)
        resetForm()
      }
    } catch (error) {
      console.error(isEditMode.value ? '更新版本失败' : '创建版本失败', error)
      const message = ResponseParser.extractMessage(error) || (isEditMode.value ? '更新版本失败，请稍后重试' : '创建版本失败，请稍后重试')
      ElMessage.error(message)
    } finally {
      submitting.value = false
    }
  })
}

const handleClose = () => {
  emit('update:modelValue', false)
}

const resetForm = () => {
  form.name = ''
  form.version_number = ''
  form.project_id = ''
  form.status = defaultState.value?.code || ''
  form.release_type = ReleaseType.MINOR
  form.environment = Environment.DEVELOPMENT
  form.planned_release_date = undefined
  form.planned_work_hours = undefined
  form.description = ''
  projectKeyword.value = ''
  projectOptions.value = projectOptions.value || []
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}
</script>

<style scoped>
.version-dialog :deep(.el-dialog__header) {
  padding: 24px 24px 16px;
  border-bottom: 1px solid #ebeef5;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  margin: 0;
}

.version-dialog :deep(.el-dialog__title) {
  font-size: 20px;
  font-weight: 600;
  color: #fff;
  display: flex;
  align-items: center;
  gap: 8px;
}

.version-dialog :deep(.el-dialog__headerbtn) {
  top: 24px;
  right: 24px;
}

.version-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #fff;
  font-size: 20px;
}

.version-dialog :deep(.el-dialog__headerbtn:hover .el-dialog__close) {
  color: #f0f0f0;
}

.version-dialog :deep(.el-dialog__body) {
  padding: 0;
  background-color: #f5f7fa;
}

.dialog-content {
  padding: 24px;
  min-height: 400px;
}

.version-form {
  background-color: #fff;
  border-radius: 8px;
  padding: 24px;
}

.form-section {
  margin-bottom: 32px;
  padding-bottom: 24px;
  border-bottom: 1px solid #f0f0f0;
}

.form-section:last-of-type {
  margin-bottom: 0;
  padding-bottom: 0;
  border-bottom: none;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid #409eff;
}

.section-icon {
  font-size: 18px;
  color: #409eff;
}

.version-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.version-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
  padding-right: 16px;
}

.version-form :deep(.el-input__wrapper) {
  border-radius: 6px;
  transition: all 0.3s;
}

.version-form :deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.version-form :deep(.el-input.is-focus .el-input__wrapper) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.version-form :deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
}

.version-form :deep(.el-textarea__inner) {
  border-radius: 6px;
  transition: all 0.3s;
}

.version-form :deep(.el-textarea__inner:hover) {
  border-color: #c0c4cc;
}

.version-form :deep(.el-textarea__inner:focus) {
  border-color: #409eff;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  background-color: #fafafa;
  border-top: 1px solid #ebeef5;
}

.button-icon {
  margin-right: 4px;
}

.version-dialog :deep(.el-input-number) {
  width: 100%;
}

.version-dialog :deep(.el-input-number .el-input__wrapper) {
  width: 100%;
}

.version-dialog :deep(.el-date-editor) {
  width: 100%;
}

.version-dialog :deep(.el-date-editor .el-input__wrapper) {
  width: 100%;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .version-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }

  .dialog-content {
    padding: 16px;
  }

  .version-form {
    padding: 16px;
  }

  .form-section {
    margin-bottom: 24px;
    padding-bottom: 16px;
  }
}
</style>

